import '../utils/core.dart';
import 'serializable.dart';

class TokenModel extends Serializable {
  static final empty = TokenModel();

  TokenModel({
    this.accessToken = '',
    this.refreshToken = '',
    this.expireIn = 0,
    this.createTime,
  });

  TokenModel.fromJson(Json json)
      : this(
          accessToken: as<String>(json['access_token'], '')!,
          refreshToken: as<String>(json['refresh_token'], '')!,
          expireIn: as<int>(json['expire_in'], 0)!,
          createTime: as<DateTime>(json['update_time'] ?? json['create_time']),
        );

  final String accessToken;
  final int expireIn;
  final String refreshToken;
  final DateTime? createTime;

  bool get isValid => accessToken.isNotEmpty;

  bool get isExpire =>
      createTime == null ||
      DateTime.now().difference(createTime!).inSeconds > expireIn;

  @override
  Json toJson() => {
        'access_token': accessToken,
        'refresh_token': refreshToken,
        'expire_in': expireIn,
        'create_time': createTime?.toString(),
      };
}
